﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Management;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.Data.SqlClient;
using Microsoft.ConfigurationManagement.ManagementProvider;
using Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine;

namespace AppImporter
{
    public partial class LimCollectionBrowse : Form
    {
        private System.Collections.ArrayList arrPackageFolders;
        public object SCCMWQLConnection;
        public XmlDocument guiConfig = new XmlDocument();

        static void LimCollectionBrowse_Main(string[] args)
        {

        }

        public LimCollectionBrowse()
        {
            guiConfig.Load(@".\Settings.xml");
            arrPackageFolders = new System.Collections.ArrayList();
            InitializeComponent();
        }

        public event ValueUpdatedEventHandler ValueUpdated;

        #region Functions


        private string PkgfldDetails(string ContainerNodeID)
        {
            System.Collections.ArrayList aResult = new System.Collections.ArrayList();

            ManagementObjectSearcher searcher = new ManagementObjectSearcher("\\\\" + guiConfig.SelectSingleNode("/AppImporter/SCCMServer").InnerText + "\\root\\SMS\\site_" + guiConfig.SelectSingleNode("/AppImporter/SCCMSiteCode").InnerText, "SELECT Name,ContainerNodeID,ParentContainerNodeID FROM SMS_ObjectContainerNode WHERE SearchFolder = 0 AND ObjectType = " + guiConfig.SelectSingleNode("/AppImporter/AppImpType").InnerText + " AND ContainerNodeID = " + ContainerNodeID);
            string ContainerName = null;

            foreach (ManagementObject qresult in searcher.Get())
            {
                ContainerName = qresult["Name"].ToString();
            }

            return ContainerName.ToString();

            //return PkgfldDetails(CollectionID, "*");
        }

        private string CollDetails(string ContainerNodeID)
        {
            lv_limcollid.Items.Clear();

            if (ContainerNodeID == "0")
            {
                string CollType;
                switch (guiConfig.SelectSingleNode("/AppImporter/AppImpType").InnerText)
                {
                    case "5000":
                        CollType = "2";
                        break;
                    case "5001":
                        CollType = "1";
                        break;
                    default:
                        CollType = "2";
                        break;
                }

                
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("\\\\" + guiConfig.SelectSingleNode("/AppImporter/SCCMServer").InnerText + "\\root\\SMS\\site_" + guiConfig.SelectSingleNode("/AppImporter/SCCMSiteCode").InnerText, "Select Name,CollectionID from SMS_Collection WHERE CollectionType = " + CollType + " AND CollectionID NOT IN (Select InstanceKey From SMS_ObjectContainerItem)");

                string ContainerName = null;

                foreach (ManagementObject qresult in searcher.Get())
                {
                    ListViewItem lvitem = new ListViewItem(new[] { qresult["Name"].ToString(), qresult["CollectionID"].ToString() });
                    lv_limcollid.Items.Add(lvitem);

                    ContainerName = qresult["Name"].ToString();
                }
                return ContainerName.ToString();
            }
            else
            {
                    ManagementObjectSearcher searcher = new ManagementObjectSearcher("\\\\" + guiConfig.SelectSingleNode("/AppImporter/SCCMServer").InnerText + "\\root\\SMS\\site_" + guiConfig.SelectSingleNode("/AppImporter/SCCMSiteCode").InnerText, "SELECT MemberGuid,MemberID,InstanceKey FROM SMS_ObjectContainerItem WHERE ObjectType = " + guiConfig.SelectSingleNode("/AppImporter/AppImpType").InnerText + " AND ContainerNodeID = " + ContainerNodeID);

                    string ContainerName = null;

                    if (searcher.Get().Count != 0)
                    {
                        foreach (ManagementObject qresult in searcher.Get())
                        {
                            ManagementObjectSearcher collsearcher = new ManagementObjectSearcher("\\\\" + guiConfig.SelectSingleNode("/AppImporter/SCCMServer").InnerText + "\\root\\SMS\\site_" + guiConfig.SelectSingleNode("/AppImporter/SCCMSiteCode").InnerText, "SELECT Name,CollectionID FROM SMS_Collection WHERE CollectionID = '" + qresult["InstanceKey"].ToString() + "'");

                            foreach (ManagementObject coll in collsearcher.Get())
                            {

                                ListViewItem lvitem = new ListViewItem(new[] { coll["Name"].ToString(), coll["CollectionID"].ToString() });
                                lv_limcollid.Items.Add(lvitem);
                            }
                        }
                    }
                    ContainerName = "Bla";
                    return ContainerName.ToString();

            }

        }

        private String[] SubPgmFld(string ContainerNodeID)
        {

            try
            {
                System.Collections.ArrayList aResult = new System.Collections.ArrayList();

                ManagementObjectSearcher searcher = new ManagementObjectSearcher("\\\\" + guiConfig.SelectSingleNode("/AppImporter/SCCMServer").InnerText + "\\root\\SMS\\site_" + guiConfig.SelectSingleNode("/AppImporter/SCCMSiteCode").InnerText, "SELECT Name,ContainerNodeID,ParentContainerNodeID FROM SMS_ObjectContainerNode WHERE SearchFolder = 0 AND ObjectType = " + guiConfig.SelectSingleNode("/AppImporter/AppImpType").InnerText + " AND ParentContainerNodeID = " + ContainerNodeID);

                foreach (ManagementObject qresult in searcher.Get())
                {
                    //MessageBox.Show(qresult["ContainerNodeID"].ToString());
                    aResult.Add(qresult["ContainerNodeID"].ToString());
                }

                return aResult.ToArray(typeof(string)) as string[];
            }
            catch (ManagementException e)
            {
                MessageBox.Show("An error occurred while querying for WMI data: " + e.Message + e.ErrorInformation);
                return null;
            }

        }



        #endregion

        private void LimCollectionBrowse_Load(object sender, EventArgs e)
        {
            this.SCCMWQLConnection = this.Connect(guiConfig.SelectSingleNode("/AppImporter/SCCMServer").InnerText);

            string[] sCols = SubPgmFld("0");
            foreach (string sCol in sCols)
            {
                TreeNode tNode = new TreeNode(PkgfldDetails(sCol).ToString());
                tNode.Tag = sCol;
                tNode.Name = sCol;
                tNode.Nodes.Add("");
                treeView1.Nodes[0].Nodes.Add(tNode);
            }

            treeView1.Sort();

            bt_collection_select.Enabled = false;

        }

        private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            if (e.Node.Nodes.Count == 1 && e.Node.Nodes[0].Text == "")
            {
                if (e.Node.Nodes[0].Text == "")
                {
                    e.Node.Nodes.Clear();
                }

                string sRoot = e.Node.Tag.ToString();
                string[] sCols = SubPgmFld(sRoot);
                foreach (string sCol in sCols)
                {
                    TreeNode tNode = new TreeNode(PkgfldDetails(sCol).ToString());
                    tNode.Tag = sCol;
                    tNode.Name = sCol;
                    tNode.Nodes.Add("");
                    e.Node.Nodes.Add(tNode);
                }
            }


        }

        private void bt_collection_select_Click(object sender, EventArgs e)
        {

            string newValue = lv_limcollid.SelectedItems[0].SubItems[1].Text.ToString() + ';' + lv_limcollid.SelectedItems[0].SubItems[0].Text.ToString();

            ValueUpdatedEventArgs valueArgs = new ValueUpdatedEventArgs(newValue);
            ValueUpdated(this, valueArgs);
            Dispose();
        }

         public void CreateConsoleFolder(WqlConnectionManager connection, string name, Int32 objectType, Int32 parentNodeID)
        {
            try
            {
                IResultObject folder = connection.CreateInstance("SMS_ObjectContainerNode");
                folder["Name"].StringValue = name;
                folder["ObjectType"].IntegerValue = objectType;
                folder["ParentContainerNodeID"].IntegerValue = parentNodeID;

                folder.Put();
            }
            catch (SmsException e)
            {
                Console.WriteLine("Failed to create folder. Error: " + e.Message);
                throw;
            }
        }

         private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
         {
             //MessageBox.Show(treeView1.SelectedNode.Name.ToString());
             this.Cursor = Cursors.WaitCursor;
             CollDetails(treeView1.SelectedNode.Name.ToString());
             bt_collection_select.Enabled = false;
             this.Cursor = Cursors.Default;
         }

         private void lv_limcollid_SelectedIndexChanged(object sender, EventArgs e)
         {
             bt_collection_select.Enabled = true;
         }

        public WqlConnectionManager Connect(string serverName)
        {
            try
            {
                SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary();
                WqlConnectionManager connection = new WqlConnectionManager(namedValues);
                if (System.Net.Dns.GetHostName().ToUpper() == serverName.ToUpper())
                {
                    connection.Connect(serverName);
                }
                else
                {
                    connection.Connect(serverName);
                }
                return connection;
            }
            catch (SmsException ex)
            {
                Console.WriteLine("Failed to Connect. Error: " + ex.Message);
                return null;
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine("Failed to authenticate. Error:" + ex.Message);
                return null;
            }
        }
    }
}
